package com.caohx.bms.controller;

import com.caohx.bms.pojo.BookCategory;
import com.caohx.bms.pojo.ResponseMessage;
import com.caohx.bms.service.IBookCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/bookCategory")
public class BookCategoryController {

    @Autowired
    private IBookCategoryService bookCategoryService;

    // 增加图书分类
    @PostMapping
    public ResponseMessage add(@Validated @RequestBody BookCategory bookCategory) {
        BookCategory category = bookCategoryService.add(bookCategory);
        return ResponseMessage.success(category);
    }

    // 修改图书分类
    @PutMapping
    public ResponseMessage edit(@Validated @RequestBody BookCategory bookCategory) {
        if (bookCategory.getId() == null) {
            throw new IllegalArgumentException("图书分类ID不能为空");
        }
        BookCategory category = bookCategoryService.edit(bookCategory);
        return ResponseMessage.success(category);

    }

    // 删除图书分类
    @DeleteMapping("/{categoryId}")
    public ResponseMessage delete(@PathVariable Long categoryId) {
        bookCategoryService.delete(categoryId);
        return ResponseMessage.success(null);
    }

    // 查询指定ID的图书分类
    @GetMapping("/detail/{categoryId}")
    public ResponseMessage get(@PathVariable Long categoryId) {
        BookCategory category = bookCategoryService.get(categoryId);
        return ResponseMessage.success(category);
    }

    // 分页查询图书分类
    @GetMapping("/list")
    public ResponseMessage listCategories(@RequestParam(defaultValue = "0") int page,
                                          @RequestParam(defaultValue = "10") int size,
                                          BookCategory query) {
        PageRequest pageRequest = PageRequest.of(page, size);
        Page<BookCategory> categoryPage = bookCategoryService.findCategories(pageRequest);
        return ResponseMessage.success(categoryPage);
    }
}
